package 回溯;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author TTDB
 * @create 2025/9/18
 */
public class solveNQueens {
     public List<List<String>> solveNQueens(int n) {
        List<List<String>> res = new ArrayList<>();
        char[][] board = new char[n][n];
        for (char[] c : board) {
            Arrays.fill(c, '.');
        }
        dfs(res, board, 0);
        return res;
    }
    public void dfs(List<List<String>> res, char[][] board, int row) {
         if (row == board.length) {
            res.add(construct(board));
            return;
        }
         for (int i = 0; i < board.length; i++) {
             if (isValid(board, row, i)) {
                 board[row][i] = 'Q';
                 dfs(res, board, row + 1);
                 board[row][i] = '.';
             }
         }
    }

    // 是否可以在 board[row][col] 放置皇后？
    private boolean isValid(char[][] board, int row, int i) {
        int n = board.length;
        // 检查列是否有皇后互相冲突
        for (int k = 0; k < n; k++) {
            if (board[k][i] == 'Q') return false;
        }
        // 检查右上方是否有皇后互相冲突
        for (int k = row - 1, l = i + 1; k >= 0 && l < n; k--, l++) {
            if (board[k][l] == 'Q') return false;
        }

        // 检查左上方是否有皇后互相冲突
        for (int k = row - 1, l = i - 1; k >= 0 && l >= 0; k--, l--) {
            if (board[k][l] == 'Q') return false;
        }

        return true;
    }
    private List<String> construct(char[][] board) {
         List<String> res = new ArrayList<>();
         for (char[] c : board) {
             res.add(new String(c));
         }
         return res;
    }

}
